/*
 * author      : 吴中勤 
 * date        : 2018/11/18
 * description : TODO
 */

package org.wzq.learn;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class MyFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(MyFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String xRequestId = genXRequestId();
        ctx.addZuulRequestHeader("x-request-id", xRequestId);
        ctx.addZuulResponseHeader("x-request-id", xRequestId);

/*        HttpServletRequest request = ctx.getRequest();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("token");
        if(accessToken == null) {
            log.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            }catch (Exception e){
                e.printStackTrace();
            }

            return null;
        }
        log.info("ok");
*/
        return null;
    }

    // 生成 随机 x-request-id 字符串
    private static String genXRequestId() {
        final int length = 10;
        final boolean useLetters = true;
        final boolean useNumbers = false;
        String uuid = RandomStringUtils.random(length, useLetters, useNumbers);
        return uuid;
    }
}